package cn.kgc.vue.controller;

import cn.kgc.vue.commons.QueryCondition;
import cn.kgc.vue.commons.ResponseResult;
import cn.kgc.vue.entity.Student;
import cn.kgc.vue.service.StudentService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author 课工场
 * @date 2024/4/17
 * @description
 */
@RestController
@RequestMapping("student")
@Api(tags = "学生模块")
public class StudentController {

    @Resource
    private StudentService studentService;

    @PostMapping("page")
    @ApiOperation("分页数据")
    public ResponseResult studentPage(@RequestBody QueryCondition<Student> queryCondition) {

        return studentService.studentPage(queryCondition);
    }

    @PostMapping("addOrUpdate")
    @ApiOperation("添加或修改学生信息")
    public ResponseResult addOrUpdateStudent(@RequestBody Student student) {

        // 判定学号不能重复
        String studentNo = student.getStudentNo();
        LambdaQueryWrapper<Student> lambda = new QueryWrapper<Student>().lambda();
        lambda.eq(Student::getStudentNo,studentNo);
        Student one = studentService.getOne(lambda);
        Integer formId = student.getId();

        if (ObjectUtils.isNotNull(one)){
            Integer DBId = one.getId();
            if (DBId.equals(formId)){
                studentService.saveOrUpdate(student);
                return  ResponseResult.success();
            }
            return  ResponseResult.fail().message(studentNo+"学号已存在");
        }

        studentService.saveOrUpdate(student);

        return ResponseResult.success() ;
    }

    @GetMapping("getById/{id}")
    @ApiOperation("根据id查询学生信息")
    public ResponseResult getStudentById(@PathVariable("id") Integer id) {

        Student student = studentService.getById(id);
        return ResponseResult.success().data("student",student);
    }


    @DeleteMapping("delete/{id}")
    @ApiOperation("根据id删除学生信息")
    public ResponseResult deleteStudentById(@PathVariable("id") Integer id) {

        studentService.removeById(id);
        return ResponseResult.success().message("删除成功");
    }

    @PostMapping("import")
    @ApiOperation("批量导入")
    public ResponseResult importStudent(MultipartFile file) throws Exception {

        return studentService.importStudent(file);
    }

    @PostMapping("export")
    @ApiOperation("批量导出")
    public void exportStudent(HttpServletResponse response, @RequestBody Map<String,Object> exportParams) throws Exception {
        System.out.println("exportParams = " + exportParams);
        studentService.exportStudent(response,exportParams);
    }
}
